const CompressionWebpackPlugin = require('compression-webpack-plugin')
const VueFilenameInjector = require('@d2-projects/vue-filename-injector')
const ThemeColorReplacer = require('webpack-theme-color-replacer')
const forElementUI = require('webpack-theme-color-replacer/forElementUI')
const cdnDependencies = require('./dependencies-cdn')
const webpack = require('webpack')
const { chain, set, each } = require('lodash')
// 拼接路径
const resolve = (dir) => require('path').join(__dirname, dir)
const {appInfo}=require('./src/setting')

let CONFIG = {
  // 基础路径 注意发布之前要先修改这里
  path: appInfo.path,
  // 是否显示源码
  view: appInfo.view,
  // 源码名称？
  viewName: appInfo.viewName,
  // 项目名称
  name: appInfo.title,
  // 分析工具
  link: appInfo.link,
}
//项目名称
process.env.VUE_APP_TITLE = CONFIG.name
//开发阶段无法使用./
if (process.env.NODE_ENV === 'development') {
  CONFIG.path = '/'
} else {
  CONFIG.path = './'
}
// 设置不参与构建的库
const externals = {}
cdnDependencies.forEach((pkg) => {
  externals[pkg.name] = pkg.library
})

// 引入文件的 cdn 链接
const cdn = {
  css: cdnDependencies.map((e) => e.css).filter((e) => e),
  js: cdnDependencies.map((e) => e.js).filter((e) => e),
}

// 多页配置，默认未开启，如需要请参考 https://cli.vuejs.org/zh/config/#pages
const pages = undefined
// const pages = {
//   index: './src/main.js',
//   subpage: './src/subpage.js'
// }

module.exports = {
  // 根据你的实际情况更改这里
  publicPath: CONFIG.path,
  lintOnSave: false, //ESlint
  outputDir: 'dist', //输出文件
  assetsDir: 'assets', //静态资源文件夹
  devServer: {
    // host: '127.0.0.1', //使用转发工具
    publicPath: CONFIG.path, // 和 publicPath 保持一致
    disableHostCheck: process.env.NODE_ENV === 'development', // 关闭 host check，方便使用 ngrok 之类的内网转发工具
  },
  css: {
    loaderOptions: {
      // 设置 scss 公用变量文件
      sass: {
        prependData: "@import '~@/assets/style/public.scss';",
      },
    },
  },
  pages,
  configureWebpack: (config) => {
    const configNew = {}
    // 不输出gizp压缩  production
    if (process.env.NODE_ENV !== 'production') {
      configNew.externals = externals
      configNew.plugins = [
        // gzip
        new CompressionWebpackPlugin({
          filename: '[path].gz[query]',
          test: new RegExp('\\.(' + ['js', 'css'].join('|') + ')$'),
          threshold: 10240,
          minRatio: 0.8,
          deleteOriginalAssets: false, //是否删除源文件
        }),
      ]
    }
    return configNew
  },
  // 默认设置: https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-service/lib/config/base.js
  chainWebpack: (config) => {
    /**
     * 添加 CDN 参数到 htmlWebpackPlugin 配置中
     * 已适配多页
     */
    const htmlPluginNames = chain(pages)
      .keys()
      .map((page) => 'html-' + page)
      .value()
    const targetHtmlPluginNames = htmlPluginNames.length ? htmlPluginNames : ['html']
    each(targetHtmlPluginNames, (name) => {
      config.plugin(name).tap((options) => {
        set(options, '[0].cdn', process.env.NODE_ENV === 'production' ? cdn : [])
        return options
      })
    })

    /**
     * 删除懒加载模块的 prefetch preload，降低带宽压力
     * https://cli.vuejs.org/zh/guide/html-and-static-assets.html#prefetch
     * https://cli.vuejs.org/zh/guide/html-and-static-assets.html#preload
     * 而且预渲染时生成的 prefetch 标签是 modern 版本的，低版本浏览器是不需要的
     */
    config.plugins.delete('prefetch').delete('preload')
    // 解决 cli3 热更新失效 https://github.com/vuejs/vue-cli/issues/1559
    config.resolve.symlinks(true)
    config.plugin('theme-color-replacer').use(ThemeColorReplacer, [
      {
        fileName: 'css/theme-colors.[contenthash:8].css',
        matchColors: [
          ...forElementUI.getElementUISeries('#409EFF'), // Element-ui主色系列
        ],
        externalCssFiles: ['./node_modules/element-ui/lib/theme-chalk/index.css'], // optional, String or string array. Set external css files (such as cdn css) to extract colors.
        changeSelector: forElementUI.changeSelector,
      },
    ])
    config
      // 开发环境 sourcemap 不包含列信息
      .when(process.env.NODE_ENV === 'development', (config) => config.devtool('cheap-source-map'))
      // 预览环境构建 vue-loader 添加 filename
      .when(CONFIG.view, (config) =>
        VueFilenameInjector(config, {
          propName: CONFIG.viewName,
        }),
      )
    // markdown
    config.module.rule('md').test(/\.md$/).use('text-loader').loader('text-loader').end()
    // svg
    const svgRule = config.module.rule('svg')
    svgRule.uses.clear()
    svgRule.include
      .add(resolve('src/assets/svg-icons/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'd2-[name]',
      })
      .end()
    // image exclude
    const imagesRule = config.module.rule('images')
    imagesRule
      .test(/\.(png|jpe?g|gif|webp|svg)(\?.*)?$/)
      .exclude.add(resolve('src/assets/svg-icons/icons'))
      .end()
    // 重新设置 alias
    config.resolve.alias.set('@api', resolve('src/api'))
    //解决打包后chunk.js文件过多问题
    config.plugin('chunkPlugin').use(webpack.optimize.LimitChunkCountPlugin, [
      {
        maxChunks: 4, // 必须大于或等于 1
        minChunkSize: 10000,
      },
    ])

    // 分析工具
    if (CONFIG.link) {
      config.plugin('webpack-bundle-analyzer').use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
    }
  },
  // 不输出 map 文件
  productionSourceMap: false,
  // i18n
  pluginOptions: {
    i18n: {
      locale: 'zh-chs',
      fallbackLocale: 'en',
      localeDir: 'locales',
      enableInSFC: true,
    },
  },
}
